import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAppSelector } from '@/store/hooks';
import { RoleType } from '@/types/auth';

interface AuthGuardProps {
  children: React.ReactNode;
  requiredRoles?: RoleType[];
}

const AuthGuard: React.FC<AuthGuardProps> = ({ children, requiredRoles }) => {
  const location = useLocation();
  const { isLoggedIn, userInfo } = useAppSelector((state) => state.auth);

  // 检查是否登录
  if (!isLoggedIn || !userInfo) {
    // 将当前路由信息保存在 state 中，登录后可以跳回来
    return <Navigate to="/auth/login" state={{ from: location }} replace />;
  }

  // 检查角色权限
  if (requiredRoles && requiredRoles.length > 0) {
    const hasRequiredRole = requiredRoles.includes(userInfo.roleType);
    if (!hasRequiredRole) {
      // 如果没有所需权限，重定向到 403 页面
      return <Navigate to="/403" replace />;
    }
  }

  return <>{children}</>;
};

export default AuthGuard; 